package io.github.doc.action.language.engine;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import io.github.doc.action.element.FileElement;
import io.github.doc.config.PluginSetting;
import io.github.doc.config.state.PluginSettingsState;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.runtime.RuntimeConstants;
import org.apache.velocity.runtime.resource.ResourceManagerImpl;
import org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader;

import java.io.StringWriter;
import java.util.Objects;
import java.util.Properties;

public class VelocityTemplateEngine implements TemplateEngine {


    /**
     * Plugin settings state
     */
    private final PluginSettingsState pluginSettingsState;

    /**
     * Velocity engine
     */
    private final VelocityEngine velocityEngine;

    /**
     * <p>Company: 深圳振瀚信息技术有限公司成都分公司 </p>
     * <p>Description: </p>
     *
     * @author ZH.Team
     * @version 1.0.0
     * @email "mailto:ZH.Team@zhxx.com"
     * @date 2025.01.26 15:10
     * @since y.y.y
     */
    public VelocityTemplateEngine(PluginSettingsState pluginSettingsState) {
        this.pluginSettingsState = pluginSettingsState;
        this.velocityEngine = new VelocityEngine();
        Properties properties = new Properties();
        // 设置模板路径
        properties.setProperty("file.resource.loader.path", "src/main/resources/template");
        properties.setProperty("input.encoding", "UTF-8"); // 设置输入文件的编码
        properties.setProperty("output.encoding", "UTF-8"); // 设置输出文件的编码
        properties.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        properties.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        this.velocityEngine.setProperty(RuntimeConstants.RESOURCE_MANAGER_INSTANCE, new ResourceManagerImpl());
        this.velocityEngine.init(properties);
    }

    /**
     * Render
     *
     * @param template template
     * @param data     data
     * @return the string
     * @since y.y.y
     */
    @Override
    public String render(String template, FileElement<?> data) {
        VelocityContext context = new VelocityContext();
        // 添加utils参数
        context.put("str", new StrUtil());
        context.put("date", new DateUtil());
        context.put("element", data);
        PluginSetting pluginSetting = this.pluginSettingsState.getState();
        if (Objects.nonNull(pluginSetting)) {
            pluginSetting.config.forEach(context::put);
        }
        // 使用VelocityEngine合并模板和上下文数据
        StringWriter writer = new StringWriter();
        velocityEngine.evaluate(context, writer, "VelocityTemplateEngine", template);
        return writer.toString();
    }
}
